/*
 * @Description:
 * @Author: LCL
 * @Date: 2021-11-18
 * @LastEditors: LCL
 * @LastEditTime: 2021-12-01
 * @FilePath: /beff/src/components/ComponentConfig/subForm/SubForm.tsx
 */
import { Form, Input, Space, Select, Switch, Tooltip } from 'antd';
import { MinusCircleOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import type { StoreValue } from 'antd/es/form/interface';
import styles from './subForm.less';

import {
  titleRender,
  fieldRender,
  checkRender,
  descRender,
  fieldPermissionsRender,
} from '@/components/ComponentConfig/commonItem';
import compDataTemp from '@/pages/Drag/compDataTemp';

type PropsType = {
  config: any;
  onChangeCallback: Function;
};

const SubForm = (props: PropsType) => {
  const { config } = props;
  const [showLimit, setShowLimit] = useState(false);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [initVals,setInitVals] = useState<any>({});
  useEffect(() => {
    const initialVals = { ...config, children: config.children[0] }
    setInitVals(initialVals)
    form.setFieldsValue(initialVals);    
  }, [config,config.children]);

  const onValuesChange = (changeValue: any, allValue: any) => {
    // console.log(allValue);

    for (const k in changeValue) {
      // const { required, label, name, layout, ...subForm } = allValue;
      const stickyColumn = { enable: allValue.enable || false, limit: allValue.limit || 0 };

      if (k === 'children') {
        config[k][0] = allValue[k];
      } else {
        config[k] = allValue[k];
      }

      config.stickyColumn = stickyColumn;
    }
    props.onChangeCallback(config);
    // console.log('config', config);

    if (Object.keys(changeValue)[0] === 'enable') {
      setShowLimit(!showLimit);
    }

    // const obj = JSON.parse(JSON.stringify(componentsConfig));
    // obj.commonForm = commonForm;
    // obj.subForm = { children: subForm.list, stickyColumn, type: 'subForm' };
    // console.log(obj);
    // setComponentsConfig(obj);
  };

  const getMenu = (add: (defaultValue?: StoreValue, insertIndex?: number) => void) => {
    const handleClick = (e: any) => {
      setVisible(false);

      const compType = e.target.dataset.type;

      const subs = ['input', 'select', 'datePicker', 'dateRange'];
      if (!subs.some((v) => v === compType)) return;
      const temp = compDataTemp()[compType];

      add(temp);
    };
    const ul = (
      <ul className={styles.menu} onClick={handleClick}>
        <li className={styles.menuItem} data-type="input">
          文本组件
        </li>
        <li className={styles.menuItem} data-type="datePicker">
          日期
        </li>
        <li className={styles.menuItem} data-type="dateRange">
          日期范围
        </li>
        <li className={styles.menuItem} data-type="select">
          下拉框
        </li>
      </ul>
    );

    return ul;
  };

  return (
    <div>
      {titleRender(config, props, 'title')}
      {fieldRender(config, props, 'field')}
      {descRender(config, props, 'describe')}
      <Form
        form={form}
        layout="vertical"
        onValuesChange={onValuesChange}
        initialValues={initVals}
      >
        <span>子字段</span>
        <Form.List name="children">
          {(fields, { add, remove }) => {
            return (
              <>
                {fields.map(({ key, name, fieldKey, ...restField }) => {
                  return (
                    <Space
                      key={key}
                      style={{ display: 'flex', marginBottom: '5px' }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'title']}
                        fieldKey={[fieldKey, 'title']}
                        className={styles.noMargin}
                      >
                        <Input disabled={true} />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  );
                })}
                <Form.Item>
                  <Tooltip title={getMenu(add)} color="white" trigger="click" visible={visible}>
                    <span
                      className={styles.add}
                      onClick={() => {
                        setVisible(true);
                      }}
                    >
                      添加子字段
                    </span>
                  </Tooltip>
                </Form.Item>
              </>
            );
          }}
        </Form.List>

        <Form.Item label="列固定" name="enable" valuePropName="checked">
          <Switch />
        </Form.Item>
        {showLimit && (
          <Form.Item label="固定列数（前）" name="limit">
            <Select>
              <Select.Option value={1}>1</Select.Option>
              <Select.Option value={2}>2</Select.Option>
              <Select.Option value={3}>3</Select.Option>
              <Select.Option value={4}>4</Select.Option>
            </Select>
          </Form.Item>
        )}
      </Form>
      {fieldPermissionsRender(config, props, 'fieldPermissions')}
      {checkRender(config, props, 'check')}
    </div>
  );
};

export default SubForm;
